package cn.apotato.dynamicdatascore.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Import(MasterDataSourceProperties.class)
@Configuration
public class DynamicDataSourceConfig {

    @Autowired
    private MasterDataSourceProperties masterDataSourceProperties;

    @Reference
    @Bean
    public DynamicDataSource dynamicDataSource() {
        DataSource defaultDataSource = masterDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", defaultDataSource);
        // 添加租户数据源
        targetDataSources.put("tenant1", buildDataSource(
                "com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://192.168.1.226:3307/test_1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&allowMutiQueries=true&useSSL=false&allowPublicKeyRetrieval=true",
                "admin",
                "ROOTabc@1234_")
        );
        targetDataSources.put("tenant2", buildDataSource(
                "com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://192.168.1.226:3307/test_2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&allowMutiQueries=true&useSSL=false&allowPublicKeyRetrieval=true",
                "admin", "ROOTabc@1234_")
        );
        return new DynamicDataSource(defaultDataSource, targetDataSources);
    }

    public DataSource masterDataSource() {
        return buildDataSource();
    }

    private DataSource buildDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(masterDataSourceProperties.getDriverClassName());
        dataSource.setUrl(masterDataSourceProperties.getUrl());
        dataSource.setUsername(masterDataSourceProperties.getUsername());
        dataSource.setPassword(masterDataSourceProperties.getPassword());
        return dataSource;
    }

    private DataSource buildDataSource(String driverClassName, String url, String username, String password) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

